package com.jswlw.controller.distributor;

import com.jswlw.controller.BaseController;
import com.jswlw.entity.base.User;
import com.jswlw.entity.biz.Distributor;
import com.jswlw.service.base.UserService;
import com.jswlw.service.biz.DistributorService;
import com.jswlw.web.manager.DistributorUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.Map;

import static com.jswlw.common.Constants.*;

/**
 * @author 吴维斌 E-mail:wuweibin0817@163.com
 * @version 创建时间：${date} ${time}
 */
@Controller
@RequestMapping("/distributor/login")
public class DistributorLoginController extends BaseController {

    @Autowired
    UserService userService;

    @Autowired
    DistributorService distributorService;

    @RequestMapping("index")
    public ModelAndView login() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/distributor/login");
        return modelAndView;
    }

    @PostMapping(value = "/doLogin")
    @ResponseBody
    public Map doLogin(HttpSession session, User loginUser) {
        Map map = userService.login(loginUser.getLoginName(), loginUser.getPassword());
        if ((int) map.get(CODE) == 0) {
            //设计经销商其他附属信息
            User user = (User) map.get(DATA);
            Distributor distributor = distributorService.find4Id(Integer.parseInt(user.getLoginName()));

            session.setAttribute("DistributorUser", DistributorUser.builder()
                    .userId(user.getId())
                    .name(distributor.getName())
                    .distributorId(distributor.getId())
                    .address(distributor.getAddress())
                    .linkMan(distributor.getLinkMan())
                    .level(distributor.getLevel())
                    .linkTel(distributor.getLinkTel())
                    .childrenIds(distributorService.getChildrenIds(distributor.getId()))
                    .build());
        }
        return map;
    }

    @RequestMapping("loginOut")
    public ModelAndView loginOut(HttpSession session) {
        ModelAndView modelAndView = new ModelAndView();
        session.removeAttribute("DistributorUser");
        modelAndView.setViewName("/distributor/login");
        return modelAndView;
    }
}
